'use strict';
const net = require("net"), fs = require('fs'), loger = require("./module/wloger");
let rIP = "192.168.0.209", rPort = 8060;

if (process.argv[2]) global.SERVERID = parseInt(process.argv[2]);
if(SERVERID > 0){
    global.LOG = loger.init(SERVERID);
    const {room} = require("./config/room.json"), rmc = require("./config/gamelist");
    for(let k in room){
        for(let i=0;i<room[k][0].length;i++){
            if(SERVERID == room[k][0][i][0]){
                global.KINDID = k;
                global.ROOMCFG = rmc[global.KINDID];
                break;
            }
        }
    }
}else{
    console.log("need serverId");
    return;
}
if (process.argv[3]) rIP = process.argv[3];
if (process.argv[4]) rPort = process.argv[4];

process.on('uncaughtException', function(err) {
    LOG.error('uncaughtException: ', err.stack);
});

global.USER = {}; //缓存当前在线的用户
global.TABLE = {}; //缓存桌子
global.CLIENT = null; //连接router的socket

function socketRun(c) {
    LOG.error('client connected');

    let olddata = null; //旧数据缓存
    c.on('data', function(data) {
        let runData = { len: 0, serverid: 0, index: 0, userid: 0, channelid: 0, M:-1, S:-1, json: {} };
        if (olddata) {
            data = Buffer.concat([olddata, data]);
            olddata = null;
        }

        while (data.length > 0) {
            runData.len = data.readUInt16LE(0);
            if (data.length >= runData.len) {
                if (runData.len < 16) {
                    data = data.slice(runData.len);
                    runData.len = 0;
                    continue;
                }
                let msg = require(".config/msg.js");
                runData.serverid = data.readUInt16LE(2);
                runData.index = data.readUInt32LE(4);
                runData.M = data.readUInt8(7);
                runData.userid = data.readUInt32LE(8);
                runData.channelid = data.readUInt32LE(12);
                runData.json = data.slice(16, runData.len);

                if (runData.json[0] == '[') {
                    try {
                        runData.json = JSON.parse(runData.json);
                        runData.S = json[1];
                    } catch (e) {
                        LOG.error(runData.json, runData.len, data.length);
                        runData.json = '';
                        break;
                    }
                }else{
                    runData.S = runData.json.readUInt16LE(6);
                }

                LOG.info(runData.userid, runData.json);
                if (runData.json && runData.M in msg.msgconfig) {
                    let filestr = msg.msgconfig[runData.M];
                    let udata = { serverid: runData.serverid, index: runData.index, userid: runData.userid, channelid: runData.channelid, M:runData.M, S:runData.S, json: runData.json };
                    udata.U = USER[runData.userid];
                    let runObj = require(filestr);
                    runObj.run(udata);
                } else {
                    LOG.error('not msg :', runData.M, runData.json);
                }
                data = data.slice(runData.len);
                runData.len = 0;
            } else {
                olddata = data;
                break;
            }
        }
    });

    c.on('end', function() {
        LOG.error('client disconnected');
        linkRooter();
    });

    c.on('error', function(e) {
        LOG.error('client error:' + c + " " + e);
        linkRooter();
    });
}

//连接路由
// setTimeout(
function linkRooter() {
    if (global.CLIENT != null && global.CLIENT.destroyed == false) {
        LOG.error('lrouter error:', global.CLIENT);
        return;
    }

    global.CLIENT = net.connect(rPort, rIP, function() {
        LOG.error("connect server ok");
        var msg = require("./config/msg"),
            buf = new Buffer(256),
            len = 29;
        buf.writeUInt16LE(2, 24); //写kindid
        buf.writeUInt16LE(SERVERID, 26); //写serverid
        buf.writeUInt8(0, 28); //写serType
        for (var k in msg.msgconfig) {
            if (k < 255) {
                buf.writeUInt8(k, len);
                len += 1; //console.log("reg k", k, len);
            }
        }
        buf.writeUInt16LE(len, 0);
        buf = buf.slice(0, len);
        global.CLIENT.write(buf);
    });
    socketRun(global.CLIENT);
    fs.appendFile("run.log", new Date().toLocaleString() + "\r\n", ()=>{});
}
linkRooter();

//------------------------------------------------------------------------------------------------------------
//命令行处理
process.stdin.on('readable', function() {
    var chunk = process.stdin.read();
    if (chunk !== null) {
        var da = chunk.toString('utf8', 0, chunk.length - 2).split(' ');
        if (da[0] == 'reload') {
            //如\login\ext.js
            if (require.cache[__dirname + da[1]]) {
                var md = require(__dirname + da[1]);
                if (md.destroy) {
                    md.destroy();
                }
                delete require.cache[__dirname + da[1]];
                LOG.error(da[1] + ' cache is delete');
                require(__dirname + da[1]);
            } else {
                LOG.error(da[1] + ' not cache');
            }
        }
    }
});